package com.lindroy.androidplayer.ui.dialog

import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.databinding.DialogLoadingBinding
import com.lindroy.lib_utils.extensions.hideKeyboard
import com.lindroy.lib_utils.extensions.screenWidth

/**
 * @author Lin
 * @date 2022/2/17
 * @function
 */
class LoadingDialog : DialogFragment() {

    private var binding: DialogLoadingBinding? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.dialog_loading, container, false)
        binding?.lifecycleOwner = viewLifecycleOwner
        return binding?.root
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        binding?.root?.hideKeyboard()
    }

    override fun onResume() {
        super.onResume()
        dialog?.window?.apply {
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val dialogSize = (screenWidth * 0.25).toInt()
            setLayout(dialogSize,dialogSize)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }

    companion object {
        private val TAG = LoadingDialog::class.java.simpleName
        private fun showDialog(fm: FragmentManager) {
            (fm.findFragmentByTag(TAG) as? LoadingDialog)?.dismiss()
            LoadingDialog().showNow(fm, TAG)
        }

        private fun dismissDialog(fm: FragmentManager) {
            (fm.findFragmentByTag(TAG) as? LoadingDialog)?.dismiss()
        }

        fun show(activity: FragmentActivity) {
            showDialog(activity.supportFragmentManager)
        }

        fun show(fragment: Fragment) {
            showDialog(fragment.childFragmentManager)
        }

        fun dismiss(activity: FragmentActivity) {
            dismissDialog(activity.supportFragmentManager)
        }

        fun dismiss(fragment: Fragment) {
            dismissDialog(fragment.childFragmentManager)
        }
    }

}